﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;

public class MeshClone : EditorWindow
{
    const string STR_INTRODUCE = "复制网格数据.\n在层次中选择有网格的GameObject.";
    const string STR_OK = "开始";
    const string STR_MESH_OBJ = "网格GameObject";

    private GameObject meshObj;

    [MenuItem("Level4/Mesh/MeshClone")]
    static void Init()
    {
        EditorWindow.GetWindow<MeshClone>();
    }

    void OnGUI()
    {
        GUILayout.Label(STR_INTRODUCE);
        meshObj = EditorGUILayout.ObjectField(new GUIContent(STR_MESH_OBJ), meshObj, typeof(Object), true) as GameObject;

        if (meshObj != null && meshObj.GetComponentInChildren<MeshFilter>() != null)
        {
            if (GUILayout.Button(STR_OK))
            {
                CloneMesh();
            }
        }
    }
	
    void OnSelectionChange()
    {
        Repaint();
    }

    void CloneMesh()
    {
        string dir = AssetDatabase.GetAssetPath(meshObj);
        if(!string.IsNullOrEmpty(dir))
            dir = Directory.GetParent(dir).ToString();
        string path = "Assets" +dir + '/' + meshObj.name + "1.asset";

        Mesh oldMesh = meshObj.GetComponentInChildren<MeshFilter>().sharedMesh;
        Mesh mesh = new Mesh();
        mesh.vertices = oldMesh.vertices;
        mesh.triangles = oldMesh.triangles;
        mesh.normals = oldMesh.normals;
        mesh.uv = oldMesh.uv;
        mesh.uv1 = oldMesh.uv1;
        mesh.uv2 = oldMesh.uv2;
        mesh.tangents = oldMesh.tangents;

        AssetDatabase.CreateAsset(mesh, path);
        ShowNotification(new GUIContent("ok"));
    }

}
